package com.lenovo.smarttraffic.ui.fragment.stage8;

import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lenovo.smarttraffic.Constant;
import com.lenovo.smarttraffic.InitApp;
import com.lenovo.smarttraffic.MainActivity;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.bean.NewsInfofBean;
import com.lenovo.smarttraffic.bean.SpotInfoBean;
import com.lenovo.smarttraffic.ui.activity.Item1Activity;
import com.lenovo.smarttraffic.ui.activity.stage8.NewsActivity;
import com.lenovo.smarttraffic.ui.fragment.BaseFragment;
import com.lenovo.smarttraffic.util.HttpUtils;
import com.lenovo.smarttraffic.util.ToastUtils;
import com.lenovo.smarttraffic.util.Utils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class NewsFragment extends BaseFragment {

    private int type = 1;

    private List<NewsInfofBean.ROWSDETAILBean> newsList = new ArrayList<>();
    private List<NewsInfofBean.ROWSDETAILBean> tempList = null;

    private Context context;
    private View view;

    private SwipeRefreshLayout swipeRefreshLayout;
    private ListView mListView;
    private NewsAdapter newsAdapter;

    public NewsFragment setType(int type) {
        this.type = type;
        return this;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    protected View getSuccessView() {
        view = LayoutInflater.from(context).inflate(R.layout.fragment_news, null);
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh);
        mListView = view.findViewById(R.id.listView);

        swipeRefreshLayout.setColorSchemeResources(R.color.Blue, R.color.Green);
        swipeRefreshLayout.setOnRefreshListener(() -> new Thread(() -> {
            Object object = requestData();

            InitApp.getHandler().post(() -> {
                refreshPage(object);
                newsAdapter.notifyDataSetChanged();
                swipeRefreshLayout.setRefreshing(false);
            });
        }).start());

        return view;
    }

    @Override
    protected Object requestData() {
        tempList = null;

        HttpUtils.post("GetNewsInfo.do", new HttpUtils().add("UserName", MainActivity.userName).add("Category", type),
                response -> {
                    newsList = new Gson().fromJson(response.toString(), NewsInfofBean.class).getROWS_DETAIL();

                    if (newsAdapter == null) {
                        tempList = new ArrayList<>();
                        for (int i = 0; i < newsList.size(); i++) {
                            if (newsList.get(i).getCategory() == type) {
                                tempList.add(newsList.get(i));
                            }
                        }
                        newsAdapter = new NewsAdapter(tempList, type);
                        mListView.setAdapter(newsAdapter);
                    } else {
                        tempList = newsAdapter.newsList;
                        int count = 0;
                        for (int i = 0; i < newsList.size(); i++) {
                            if (newsList.get(i).getCategory() == type && count < 2) {
                                count++;
                                tempList.add(0, newsList.get(i));
                            }
                        }
                        InitApp.getHandler().post(() -> ToastUtils.showCustomToast(context, "已经为您增加一组数据", Toast.LENGTH_SHORT));
                    }
                });

        SystemClock.sleep(1000);
        return tempList;
    }

    @Override
    public void onClick(View v) {

    }
}

class NewsAdapter extends BaseAdapter {

    public List<NewsInfofBean.ROWSDETAILBean> newsList;
    private List<SpotInfoBean.ROWSDETAILBean> spotList = Item1Activity.spotList;

    private int type;

    public NewsAdapter(List<NewsInfofBean.ROWSDETAILBean> newsList, int type) {
        this.newsList = newsList;
        this.type = type;
    }

    @Override
    public int getCount() {
        return type == 1 ? newsList.size() + 2 : newsList.size();
    }

    @Override
    public int getViewTypeCount() {
        return type == 1 ? 2 : 1;
    }

    @Override
    public int getItemViewType(int position) {
        //1:without pic
        //2:with pic
        if (type != 1 || position <= newsList.size() - 1) {
            return 0;
        } else return 1;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        int viewType = getItemViewType(position);

        if (convertView == null) {
            holder = new ViewHolder();

            if (viewType == 0) {
                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_news, parent, false);
            } else {
                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_news_pic, parent, false);
                holder.icon = convertView.findViewById(R.id.icon);
            }
            holder.mTitle = convertView.findViewById(R.id.title);
            holder.mTime = convertView.findViewById(R.id.time);
            holder.mInfo = convertView.findViewById(R.id.info);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        if (viewType == 0) {
            NewsInfofBean.ROWSDETAILBean bean = newsList.get(position);

            holder.mTitle.setText(bean.getTitle());
            holder.mTime.setText(bean.getCreatetime().substring(0, bean.getCreatetime().length() - 3));
            holder.mInfo.setText(bean.getContent());
        } else {
            SpotInfoBean.ROWSDETAILBean bean = spotList.get(Utils.getRandom(0, spotList.size() - 1));

            holder.mTitle.setText(bean.getName());
            holder.mTime.setText(newsList.get(0).getCreatetime().substring(0, newsList.get(0).getCreatetime().length() - 3));
            holder.mInfo.setText(bean.getInfo());

            String picUrl = Constant.urlPrefix + bean.getImg();
            Glide.with(parent.getContext()).load(picUrl).placeholder(R.drawable.page_loading).error(R.drawable.ic_error_page).into(holder.icon);
        }

        convertView.setOnClickListener(v -> {
            if (viewType == 1) {
                NewsActivity.drawable = new WeakReference<>(holder.icon.getDrawable());
            }

            parent.getContext().startActivity(new Intent(parent.getContext(), NewsActivity.class)
                    .putExtra("hasPic", viewType == 1)
                    .putExtra("type", type)
                    .putExtra("title", holder.mTitle.getText().toString())
                    .putExtra("time", holder.mTime.getText().toString())
                    .putExtra("info", holder.mInfo.getText().toString())
            );
        });

        return convertView;
    }

    static class ViewHolder {
        TextView mTitle;
        TextView mTime;
        TextView mInfo;
        ImageView icon;
    }
}